package com.cff.springbootwork.websocket.handler;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

/**
 * websocket 握手处理器
 * @author fufei
 *
 */
@Component
public class WebSocketInterceptor extends HttpSessionHandshakeInterceptor {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
		log.info("收到握手请求。");
		if (request instanceof ServletServerHttpRequest) {
			ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
			HttpSession session = servletRequest.getServletRequest().getSession(false);
			if (session == null) {
				return false;
			}
			// 使用userName区分WebSocketHandler，以便定向发送消息
			String userName = (String) session.getAttribute("userName");
			if (StringUtils.isEmpty(userName)) {
				return false;
			}
			log.info("获取到用户信息：{}", userName);
			attributes.put("userId", userName);
		}
		return super.beforeHandshake(request, response, wsHandler, attributes);
	}

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception ex) {
		log.info("成功握手。");
		super.afterHandshake(request, response, wsHandler, ex);
	}

}